package com.xxc.hs.funActivity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.textfield.TextInputLayout;
import com.xxc.hs.R;
import com.xxc.hs.funActivity.chart.ChatAdapter;
import com.xxc.hs.funActivity.chart.Message;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@SuppressWarnings("ALL")
public class ChartActivity extends AppCompatActivity {
    private static final String TAG = "ChatActivity";
    private RecyclerView chatRecyclerView;
    private EditText messageEditText;
    private ChatAdapter chatAdapter;
    private Toolbar toolbar;
    private ImageButton imageSelectButton;
    private ImageButton sendButton; // 新增发送按钮引用

    // 新增：图片预览和发送区域
    private LinearLayout pendingImageContainer;
    private ImageView pendingImageView;
    private TextView removeImageButton;
    private String selectedImagePath;

    // 线程池与HTTP客户端
    private ExecutorService executorService;

    // 阿里云API配置
    private static final String ENDPOINT = "https://dashscope.aliyuncs.com";
    private static final String API_PATH = "/compatible-mode/v1/chat/completions";
    private static final String METHOD = "POST";
    private static final String API_KEY = "sk-c25775c0a72c48c7b933689b4008506f"; // 替换为实际API Key
    private static final String MODEL_NAME = "deepseek-r1-distill-llama-70b";

    // 图片相关配置
    private static final int IMAGE_QUALITY = 80;
    private static final int IMAGE_SAMPLE_SIZE = 4;
    private static final int MAX_IMAGE_SIZE_KB = 10000; // 图片最大大小(KB)

    // 交互相关
    private static final String INITIAL_PROMPT = "AI为你解答：您好！我是您的智能助手，有什么可以帮您的吗？";
    private static final int PICK_IMAGE_REQUEST = 1;
    private Handler mainHandler;
    private int currentAiMessagePosition = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chart);
        try {
            initViews();
            setupRecyclerView();
            setupMessageEditText();
            setupImageSelectButton();
            setupSendButton(); // 新增初始化发送按钮
            addInitialPrompt();

            // 初始化组件
            executorService = Executors.newSingleThreadExecutor();
            mainHandler = new Handler(Looper.getMainLooper());
        } catch (Exception e) {
            Log.e(TAG, "初始化失败", e);
        }
    }

    private void initViews() {
        chatRecyclerView = findViewById(R.id.chatRecyclerView);
        messageEditText = findViewById(R.id.messageEditText);
        toolbar = findViewById(R.id.toolBar_chat);
        imageSelectButton = findViewById(R.id.imageSelectButton);
        sendButton = findViewById(R.id.sendButton); // 查找发送按钮

        // 初始化新增的图片预览区域
        pendingImageContainer = findViewById(R.id.pendingImageContainer);
        pendingImageView = findViewById(R.id.pendingImageView);
        removeImageButton = findViewById(R.id.removeImageButton);

        // 设置移除图片按钮事件
        removeImageButton.setOnClickListener(v -> clearSelectedImage());

        toolbar.setOnClickListener(v -> finish());
    }

    private void setupRecyclerView() {
        chatAdapter = new ChatAdapter();
        chatRecyclerView.setAdapter(chatAdapter);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setStackFromEnd(true);
        chatRecyclerView.setLayoutManager(layoutManager);
    }

    private void setupMessageEditText() {
        messageEditText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                sendMessageOrImage();
                return true;
            }
            return false;
        });

        TextInputLayout messageInputLayout = findViewById(R.id.messageInputLayout);
        messageInputLayout.setEndIconOnClickListener(v -> sendMessageOrImage());
    }

    private void setupSendButton() {
        if (sendButton != null) {
            sendButton.setOnClickListener(v -> sendMessageOrImage()); // 为发送按钮设置点击事件
        } else {
            Log.w(TAG, "发送按钮未找到，请检查布局文件");
        }
    }

    private void setupImageSelectButton() {
        imageSelectButton.setOnClickListener(v -> {
            if (selectedImagePath != null) {
                // 如果已有选中的图片，提示用户先发送或移除
                showToast("请先发送或移除已选择的图片");
                return;
            }

            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, PICK_IMAGE_REQUEST);
        });
    }

    private void addInitialPrompt() {
        Message initialMessage = new Message(Message.TYPE_AI, INITIAL_PROMPT);
        chatAdapter.addMessage(initialMessage);
        chatRecyclerView.scrollToPosition(chatAdapter.getItemCount() - 1);
    }

    private void sendMessageOrImage() {
        String messageText = messageEditText.getText().toString().trim();

        // 检查是否有选中的图片
        if (selectedImagePath != null) {
            // 有图片，无论是否有文字都发送图文消息
            if (!isNetworkAvailable()) {
                showToast("网络连接不可用，请检查网络设置");
                return;
            }

            // 检查图片大小
            long imageSizeKb = getImageSizeKb(selectedImagePath);
            if (imageSizeKb > MAX_IMAGE_SIZE_KB) {
                showToast("图片大小超过限制(" + MAX_IMAGE_SIZE_KB + "KB)，请选择更小的图片");
                return;
            }

            Message userMessage = new Message(Message.TYPE_USER, messageText, selectedImagePath, true);
            chatAdapter.addMessage(userMessage);
            messageEditText.setText("");
            chatRecyclerView.scrollToPosition(chatAdapter.getItemCount() - 1);

            // 添加AI消息占位符
            Message aiMessage = new Message(Message.TYPE_AI, "");
            chatAdapter.addMessage(aiMessage);
            currentAiMessagePosition = chatAdapter.getItemCount() - 1;
            chatRecyclerView.scrollToPosition(currentAiMessagePosition);

            // 发送图文消息
            executorService.execute(() -> {
                try {
                    String base64Image = encodeImageToBase64(selectedImagePath);
                    if (TextUtils.isEmpty(base64Image)) {
                        showToastOnMainThread("图片编码失败，请重试");
                        return;
                    }

                    Log.d(TAG, "图片Base64编码成功，长度: " + base64Image.length() / 1024 + "KB");

                    // 发送后清除选中的图片
                    mainHandler.post(this::clearSelectedImage);

                    callAliyunApi(messageText, base64Image);
                } catch (Exception e) {
                    Log.e(TAG, "图片处理异常", e);
                    showToastOnMainThread("图片处理失败：" + e.getMessage());
                }
            });
        } else {
            // 没有图片，只发送文字消息
            if (TextUtils.isEmpty(messageText)) {
                showToast("请输入消息内容");
                return;
            }

            // 原有文字消息逻辑
            Message userMessage = new Message(Message.TYPE_USER, messageText);
            chatAdapter.addMessage(userMessage);
            messageEditText.setText("");
            chatRecyclerView.scrollToPosition(chatAdapter.getItemCount() - 1);

            // 添加AI消息占位符
            Message aiMessage = new Message(Message.TYPE_AI, "");
            chatAdapter.addMessage(aiMessage);
            currentAiMessagePosition = chatAdapter.getItemCount() - 1;
            chatRecyclerView.scrollToPosition(currentAiMessagePosition);

            callAliyunApi(messageText, null);
        }
    }

    private long getImageSizeKb(String imagePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, options);
        return (options.outWidth * options.outHeight * 4) / 1024; // 估算大小(KB)
    }

    private void callAliyunApi(String userText, String base64Image) {
        try {
            // 创建HTTP客户端
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(120, TimeUnit.SECONDS)
                    .build();

            // 构建请求体
            String requestBody = buildRequestBody(userText, base64Image);
            Log.d(TAG, "API请求体: " + requestBody);

            // 创建请求
            RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestBody);
            Request request = new Request.Builder()
                    .url(ENDPOINT + API_PATH)
                    .header("Authorization", "Bearer " + API_KEY)
                    .header("Content-Type", "application/json")
                    .post(body)
                    .build();

            // 执行请求
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e(TAG, "API请求失败", e);
                    String errorMsg = "请求失败: " + e.getMessage();
                    mainHandler.post(() -> {
                        updateAiMessage(errorMsg);
                        showToast(errorMsg);
                    });
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    try {
                        if (!response.isSuccessful()) {
                            String errorBody = response.body() != null ? response.body().string() : "无响应体";
                            Log.e(TAG, "API请求失败，状态码: " + response.code() + ", 错误信息: " + errorBody);
                            String errorMsg = "请求失败: HTTP错误码 " + response.code();
                            mainHandler.post(() -> {
                                updateAiMessage(errorMsg);
                                showToast(errorMsg);
                            });
                            return;
                        }

                        String responseBody = response.body().string();
                        Log.d(TAG, "API响应成功，内容长度: " + responseBody.length());
                        final String aiResponse = parseAiResponse(responseBody);
                        mainHandler.post(() -> updateAiMessage(aiResponse));
                    } catch (Exception e) {
                        Log.e(TAG, "处理响应异常", e);
                        mainHandler.post(() -> {
                            updateAiMessage("处理响应异常: " + e.getMessage());
                            showToast("处理响应异常，请重试");
                        });
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "API调用异常", e);
            mainHandler.post(() -> {
                updateAiMessage("API调用异常: " + e.getMessage());
                showToast("请求处理失败，请重试");
            });
        }
    }

    private void updateAiMessage(String content) {
        try {
            if (currentAiMessagePosition >= 0 && currentAiMessagePosition < chatAdapter.getItemCount()) {
                Message message = chatAdapter.getItem(currentAiMessagePosition);
                if (message != null) {
                    message.setContent(content);
                    chatAdapter.notifyItemChanged(currentAiMessagePosition);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String buildRequestBody(String userText, String base64Image) {
        try {
            JSONObject request = new JSONObject();
            request.put("model", MODEL_NAME);
            request.put("stream", true); // 启用流式响应

            JSONArray messages = new JSONArray();
            JSONObject userMessageObj = new JSONObject();
            userMessageObj.put("role", "user");

            JSONArray contentArray = new JSONArray();

            // 添加文本内容
            if (!TextUtils.isEmpty(userText)) {
                JSONObject textContent = new JSONObject();
                textContent.put("type", "text");
                textContent.put("text", userText);
                contentArray.put(textContent);
            }

            // 添加图片内容
            if (!TextUtils.isEmpty(base64Image)) {
                JSONObject imageContent = new JSONObject();
                imageContent.put("type", "image_url");

                JSONObject imageUrlObj = new JSONObject();
                imageUrlObj.put("url", "data:image/jpeg;base64," + base64Image);
                imageContent.put("image_url", imageUrlObj);

                contentArray.put(imageContent);
            }

            userMessageObj.put("content", contentArray);
            messages.put(userMessageObj);
            request.put("messages", messages);

            request.put("max_tokens", 1000);
            request.put("temperature", 0.7);
            request.put("top_p", 0.9);

            return request.toString();
        } catch (JSONException e) {
            Log.e(TAG, "构建请求体失败", e);
            return "{}";
        }
    }

    private String encodeImageToBase64(String imagePath) {
        try {
            // 优化图片解码
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = IMAGE_SAMPLE_SIZE;
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);

            if (bitmap == null) {
                Log.e(TAG, "无法解码图片: " + imagePath);
                return null;
            }

            // 检查图片尺寸
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            Log.d(TAG, "图片解码后尺寸: " + width + "x" + height);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();

            Log.d(TAG, "图片压缩后大小: " + byteArray.length + " bytes (" + byteArray.length / 1024 + "KB)");
            return Base64.encodeToString(byteArray, Base64.NO_WRAP);
        } catch (Exception e) {
            Log.e(TAG, "图片编码失败", e);
            return null;
        }
    }

    private String parseAiResponse(String response) {
        if (TextUtils.isEmpty(response)) {
            return "AI未返回有效响应（空回复）";
        }

        try {
            // 处理流式响应格式
            StringBuilder contentBuilder = new StringBuilder();
            String[] lines = response.split("\n");

            for (String line : lines) {
                line = line.trim();
                if (line.startsWith("data: ") && !line.equals("data: [DONE]")) {
                    String jsonData = line.substring(6);
                    JSONObject jsonResponse = new JSONObject(jsonData);

                    JSONArray choices = jsonResponse.optJSONArray("choices");
                    if (choices != null && choices.length() > 0) {
                        JSONObject choice = choices.getJSONObject(0);
                        JSONObject delta = choice.optJSONObject("delta");

                        if (delta != null) {
                            String content = delta.optString("content", "");
                            contentBuilder.append(content);
                        }
                    }
                }
            }

            String fullContent = contentBuilder.toString();
            if (!TextUtils.isEmpty(fullContent)) {
                return fullContent;
            }

            // 传统响应解析作为 fallback
            JSONObject jsonResponse = new JSONObject(response);
            if (jsonResponse.has("error")) {
                JSONObject error = jsonResponse.getJSONObject("error");
                return "错误: " + error.optString("message", "未知错误");
            }

            JSONArray choices = jsonResponse.optJSONArray("choices");
            if (choices != null && choices.length() > 0) {
                JSONObject choice = choices.getJSONObject(0);
                JSONObject message = choice.optJSONObject("message");

                if (message != null) {
                    return message.optString("content", "AI返回空内容");
                }
            }

            return jsonResponse.optString("response", "抱歉，AI没有返回有效回复");
        } catch (JSONException e) {
            Log.e(TAG, "解析响应失败: " + response, e);
            return "解析AI回复失败: " + e.getMessage();
        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    private void showToast(final String message) {
        mainHandler.post(() -> Toast.makeText(ChartActivity.this, message, Toast.LENGTH_SHORT).show());
    }

    private void showToastOnMainThread(final String message) {
        mainHandler.post(() -> Toast.makeText(ChartActivity.this, message, Toast.LENGTH_SHORT).show());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        try {
            if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        selectedImagePath = cursor.getString(columnIndex);

                        // 显示图片预览
                        showSelectedImage(selectedImagePath);
                    }
                    cursor.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showSelectedImage(String imagePath) {
        try {
            // 加载图片预览
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 8; // 缩小预览图
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);

            if (bitmap != null) {
                pendingImageView.setImageBitmap(bitmap);
                pendingImageContainer.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void clearSelectedImage() {
        try {
            selectedImagePath = null;
            pendingImageView.setImageBitmap(null);
            pendingImageContainer.setVisibility(View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (executorService != null) {
                executorService.shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}